﻿using KPIS.GERP.SERVICE.BLL;
using KPIS.GERP.SERVICE.DAL;
using KPIS.GERP.SERVICE.Model;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;

namespace KPIS.GERP.MVC.Classes
{
    public class Common
    {
        #region Public Method

        public int GetMessageCount()
        {
            SsMng ssmng = new SsMng();

            using (GERPContext db = new GERPContext())
            {
                int count = (from m in db.message
                             where m.to_emp_seq == ssmng.EmpSeqI
                             select m).Count();
                return count;
            }
        }

        public Nullable<int> ConvertNullInt(Object o)
        {
            Nullable<int> result = o == null
                                       ? null
                                       : (o.ToString().Length == 0
                                              ? null
                                              : (Nullable<int>)Convert.ToInt32(o));
            return result;
        }

        public Nullable<double> ConvertNullDouble(Object o)
        {
            Nullable<double> result = o == null
                                          ? null
                                          : (o.ToString().Length == 0
                                                 ? null
                                                 : (Nullable<double>)Convert.ToDouble(o));
            return result;
        } 

        public Nullable<DateTime> ConvertNullDateTime(Object o)
        {
            Nullable<DateTime> result = o == null
                                            ? null
                                            : (o.ToString().Length == 0
                                                   ? null
                                                   : (Nullable<DateTime>)Convert.ToDateTime(o)
                                              );
            return result;
        }

        public Nullable<TimeSpan> ConvertNullTimeSpan(Object o)
        {
            Nullable<TimeSpan> result = o == null
                                            ? null
                                            : (o.ToString().Length == 0
                                                   ? null
                                                   : (Nullable<TimeSpan>)Convert.ToDateTime(o).TimeOfDay);
            return result;
        }

        public string ConvertDBDateTimeToString(Object o, bool bLongDateString)
        {
            string result;

            if (bLongDateString)
                result = o == DBNull.Value ? "" : Convert.ToDateTime(o).ToLongDateString();
            else
                result = o == DBNull.Value ? "" : Convert.ToDateTime(o).ToShortDateString();

            return result;
        }

        public string MakeZero(object str)
        {
            double temp;
            return !Double.TryParse(Convert.ToString(str), out temp) ? "0" : Convert.ToString(str);
        }
        public decimal MakeZeroDecimal(string str)
        { 
            try
            {
                return Convert.ToDecimal(str);
            } catch(Exception ex)
            {
                return 0;
            }
        }

        public int AlwayInt(string str)
        {
            int temp;
            return !Int32.TryParse(Convert.ToString(str), out temp) ? 0 : Convert.ToInt32(str);
        }

        public string WebString(string strValue)
        {
            string strResult = strValue.Replace("&nbsp;", "").Replace("\r\n", "<br />");

            return strResult;
        }

        public string ErrorEmtyString(string strFieldName)
        {
            string strResult = "กรูณากรอกข้อมูล [@1]".Replace("@1", strFieldName);

            return strResult;
        }

        public string EncodeHtml(string strValue = "")
        {
            string strResult = HttpUtility.HtmlEncode(strValue.Replace("'", "").Replace("\"", ""));

            return strResult;
        }

        public string DBString(string strValue)
        {
            strValue = strValue.Replace("–", "-");

            return (strValue.Length == 0 ? null : strValue);
        }

        public string LabelToTextbox(string strValue)
        {
            string strResult = strValue.Replace("<br />", "\r\n");

            return strResult;
        }

        /// <summary>
        /// If parameter str is Integer, Then return true
        /// If It empty string or space or charactor or contain number not in format int, return false
        /// </summary>
        /// <param name="str">string to check is it integer</param>
        /// <returns></returns>
        public bool IsInt32(string str)
        {
            if (String.IsNullOrEmpty(str))
                return false;

            str = str.Trim();

            int r;
            return Int32.TryParse(str, out r);
        }

        /// <summary>
        /// If parameter str is Integer or Double, Then return true
        /// If It empty string or space or charactor or contain number not in format double or int, return false
        /// </summary>
        /// <param name="str">string to check is it double or integer</param>
        /// <returns></returns>
        public bool IsDouble(string str)
        {
            if (String.IsNullOrEmpty(str))
                return false;

            str = str.Trim();

            double r;
            return Double.TryParse(str, out r);
        }

        public DateTime? CurrectDateTime(DateTime? dt)
        {
            if (dt == null)
                return null;

            int nYear = dt.Value.Year;

            if (nYear < 2400)
            {
                dt.Value.AddYears(543);
            }

            return dt;
        }

        public static string GetDateString(object date)
        {
            string strResult = "";
            if (date != null)
            {
                DateTime dt = DateTime.Today;

                if (DateTime.TryParse(date.ToString(), out dt))
                {
                    strResult = dt.ToShortDateString();
                }
            }

            return strResult;
        }

        public static string GetLongDateString(object date)
        {
            string strResult = "";

            if (date != null)
            {
                DateTime dt = DateTime.Today;

                if (DateTime.TryParse(date.ToString(), out dt))
                {
                    strResult = dt.ToLongDateString();
                }
            }

            return strResult;
        }

        public static string GetRecordStatusName(string strRecoedStatus)
        {
            string strResult = "";

            switch (strRecoedStatus)
            {
                case "A":
                    strResult = "อนุมัติแล้ว";
                    break;
                case "P":
                    strResult = "อยู่ระหว่างอนุมัติ";
                    break;
                case "W":
                    strResult = "ยังไม่ส่งอนุมัติ";
                    break;
                case "U":
                    strResult = "ใช้งานอยู่";
                    break;
                case "D":
                    strResult = "ลบแล้ว";
                    break;
                case "R":
                    strResult = "ส่งกลับ";
                    break;
                default:
                    break;
            }

            return strResult;
        }

        public static DateTime? GetDate(DateTime? dtmValueFromDatePicker)
        {
            if (dtmValueFromDatePicker == null)
            {
                return null;
            }

            if (dtmValueFromDatePicker.Value.Year < 1500)// แสดงว่าได้ค่า
            {
                return dtmValueFromDatePicker.Value.AddYears(543);
            }
            else if (dtmValueFromDatePicker.Value.Year >= 2400)
            {
                return dtmValueFromDatePicker.Value.AddYears(-2400);
            }

            return dtmValueFromDatePicker;
        }

        #endregion

        #region Properties
        public static string EssLoginUrl = ConfigurationSettings.AppSettings["EssLoginUrl"];
        public static string EssSelectSystemUrl = ConfigurationSettings.AppSettings["EssSelectSystemUrl"];
        public static string InternalLoginUrl = ConfigurationSettings.AppSettings["InternalLoginUrl"];
        public static string IssueNotLoginUrl = ConfigurationSettings.AppSettings["IssueNotLoginUrl"];
        public static string LoggedOutUrl = ConfigurationSettings.AppSettings["LoggedOutUrl"];
        public static string FullDateFormat = "d MMMM yyyy";
        public enum EditMode
        {
            AddNew,Edit,View, Info
        }

        public enum RecordStatus
        {
            /// <summary>
            /// Approved อนุมัติแล้ว
            /// </summary>
            A,
            /// <summary>
            /// Processing อยู่ระหว่างอนุมัติ
            /// </summary>
            P,
            /// <summary>
            /// Waiting ยังไม่ส่งอนุมัติ = U
            /// </summary>
            W,
            /// <summary>
            /// Used ใช้งานอยู่ = W
            /// </summary>
            U,
            /// <summary>
            /// Deleted ลบแล้ว
            /// </summary>
            D,
            /// <summary>
            /// Returned ส่งกลับ
            /// </summary>
            R
        }

        #endregion
    }

    public class SsMng
    {
        readonly Common _common = new Common();

        private const int ExpiresHour = 1;
        public string tempRedirectUrl { get; set; }

        public int PortNumber = HttpContext.Current.Request.Url.Port; //This module serverPort

        public bool IncludePortNumberInKey = false;

        public enum SsUserType
        {
            EmpSeq,
            UserName,
            UserSeq,
            WorkingJobSiteSeq,
            Height,
            UserDetail
        }

        // ถ้าต้องการเพิ่มตัวแปร Session ให้มาเพิ่มที่ตัวนี้ด้วย

        #region Get Value Zone

        public void Logout()
        {
            HttpContext.Current.Response.Cookies.Clear();
            HttpContext.Current.Request.Cookies.Clear();
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Session.Clear();
            // โหลด Cookie
            HttpCookie cookieUserDetail = HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)];
        }

        public bool IsLogin()
        {
            // โหลด Cookie
            HttpCookie cookieUserDetail = HttpContext.Current.Request.Cookies[KeyWithPort(SsUserType.UserDetail)];

            // ถ้า Cookie ไม่ได้ถูกเซต, noCookie = true
            bool noCookie = cookieUserDetail == null || !cookieUserDetail.HasKeys;

            // ถ้า Session ไม่ได้ถูกเซต , noSession = true
            bool noSession =
                string.IsNullOrWhiteSpace(Convert.ToString(HttpContext.Current.Session[KeyWithPort(SsUserType.UserSeq)]));

            // ประมวลผล #1 : ถ้า Cookie ไม่ได้ถูกเซต Session ไม่ได้ถูกเซต แสดงว่าไม่ได้ Login แน่นอน, ทำการ Redirect ไปหน้า Login
            if (noCookie && noSession)
            {
                return false;
            }

            return true;
        }

        public string GetUss(SsUserType ssUserType)
        // ดึงข้อมูล จาก Session ตาม Key ที่ระบุ, และย้ำลง/ขยายเวลาหมด Cookie ไปในตัว
        {
            // 1. Session ไม่มีค่า แต่ Cookie มีค่า
            HttpCookie cookieUserDetail = ReadAndExtendExpireCookie();
            HttpContext.Current.Session[KeyWithPort(SsUserType.EmpSeq)] =
                cookieUserDetail[KeyWithPort(SsUserType.EmpSeq)];
            HttpContext.Current.Session[KeyWithPort(SsUserType.UserName)] =
                cookieUserDetail[KeyWithPort(SsUserType.UserName)];
            HttpContext.Current.Session[KeyWithPort(SsUserType.UserSeq)] =
                cookieUserDetail[KeyWithPort(SsUserType.UserSeq)];
            HttpContext.Current.Session[KeyWithPort(SsUserType.WorkingJobSiteSeq)] =
                cookieUserDetail[KeyWithPort(SsUserType.WorkingJobSiteSeq)];
            HttpContext.Current.Session[KeyWithPort(SsUserType.Height)] =
                cookieUserDetail[KeyWithPort(SsUserType.Height)];

            if (HttpContext.Current.Session[KeyWithPort(ssUserType)] == null)
            {
                //throw new Exception("No session name [\"" + KeyWithPort(ssUserType) + "\"], but not redirect");
            }

            return Convert.ToString(HttpContext.Current.Session[KeyWithPort(ssUserType)]);
        }

        public int GetUssI(SsUserType ssUserType) // Get user session as int
        {
            int result;
            Int32.TryParse(GetUss(ssUserType), out result);
            return result;
        }

        // ดึง Session Value (String)
        /* ให้ง่ายต่อการใช้ สามารถดึง Value ของ Session ได้ผ่าน Properties เหล่านี้ทันที*/

        public string EmpSeq
        {
            get { return GetUss(SsUserType.EmpSeq); }
            set { SetUss(SsUserType.EmpSeq, value); }
        }

        public string UserName
        {
            get { return GetUss(SsUserType.UserName); }
            set { SetUss(SsUserType.UserName, value); }
        }

        public string UserSeq
        {
            get { return GetUss(SsUserType.UserSeq); }
            set { SetUss(SsUserType.UserSeq, value); }
        }

        public string WorkingJobSiteSeq
        {
            get { return GetUss(SsUserType.WorkingJobSiteSeq); }
            set { SetUss(SsUserType.WorkingJobSiteSeq, value); }
        }

        public string Height
        {
            get { return String.IsNullOrEmpty(GetUss(SsUserType.Height)) ? "500" : GetUss(SsUserType.Height); }
            set { SetUss(SsUserType.Height, value); }
        }

        public string UserDetail
        {
            get { return GetUss(SsUserType.UserDetail); }
            set { SetUss(SsUserType.UserDetail, value); }
        }

        // ดึง Session Value (Int) --> ถ้า Session มีค่าว่าง แปลงเป็น Int ไม่ได้ จะ Throw Error
        /* ให้ง่ายต่อการใช้ สามารถดึง Value ของ Session ได้ผ่าน Properties เหล่านี้ทันที*/

        public int EmpSeqI
        {
            get { return GetUssI(SsUserType.EmpSeq); }
            set { SetUss(SsUserType.EmpSeq, value); }
        }

        public int UserSeqI
        {
            get { return GetUssI(SsUserType.UserSeq); }
            set { SetUss(SsUserType.UserSeq, value); }
        }

        public int WorkingJobSiteSeqI
        {
            get { return GetUssI(SsUserType.WorkingJobSiteSeq); }
            set { SetUss(SsUserType.WorkingJobSiteSeq, value); }
        }

        public int HeightI
        {
            get { return GetUssI(SsUserType.Height) == 0 ? 500 : GetUssI(SsUserType.Height); }
            set { SetUss(SsUserType.Height, value); }
        }

        public bool HasUserCookie()
        {
            return HttpContext.Current.Request.Cookies[SsUserType.UserDetail.ToString()] != null;
        }

        public string ServerName
        {
            get
            {
                string port = HttpContext.Current.Request.Url.Port.ToString(CultureInfo.InvariantCulture);
                return HttpContext.Current.Request.Url.Host +
                    (port == "80" ? "" : ":" + port);
            }
        }

        public override string ToString()
        {
            StringBuilder result = new StringBuilder();
            result.Append("This is session<br>");
            foreach (var s in HttpContext.Current.Session.Keys)
            {
                result.Append(s);
                result.Append("=");
                result.Append(HttpContext.Current.Session[s.ToString()]);
                result.Append("<br>");
            }
            result.Append("<br>");
            result.Append("This is cookie<br>");
            HttpCookie ck = HttpContext.Current.Request.Cookies[SsUserType.UserDetail.ToString()];
            if (ck != null && ck.HasKeys)
            {
                foreach (var s in ck.Values)
                {
                    result.Append(s);
                    result.Append("=");
                    result.Append(ck[s.ToString()]);
                    result.Append("<br>");
                }
            }
            return result.ToString();
        }

        #endregion

        #region Set Value Zone

        public void SetLoginSession(string userSeq,
            string empSeq,
            string userName,
            string workingJobSiteSeq,
            string height = "600",
            bool includePortNumberInKey = false)
        {
            IncludePortNumberInKey = includePortNumberInKey;

            HttpCookie cookieUserDetail = HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)] ??
                HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)];

            if (cookieUserDetail == null)
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(KeyWithPort(SsUserType.UserDetail)));

            // Set Session 
            HttpContext.Current.Session[KeyWithPort(SsUserType.EmpSeq)] = empSeq;
            HttpContext.Current.Session[KeyWithPort(SsUserType.UserName)] = userName;
            HttpContext.Current.Session[KeyWithPort(SsUserType.UserSeq)] = userSeq;
            HttpContext.Current.Session[KeyWithPort(SsUserType.WorkingJobSiteSeq)] = workingJobSiteSeq;
            HttpContext.Current.Session[KeyWithPort(SsUserType.Height)] = height;

            // Set Cookie 
            // Remark : now if cookieUserDetail == null , meaning Can't create cookie
            if (cookieUserDetail != null)
            {
                HttpContext.Current.Session[KeyWithPort(SsUserType.EmpSeq)] =
                    cookieUserDetail[KeyWithPort(SsUserType.EmpSeq)] = empSeq;
                HttpContext.Current.Session[KeyWithPort(SsUserType.UserName)] =
                    cookieUserDetail[KeyWithPort(SsUserType.UserName)] = userName;
                HttpContext.Current.Session[KeyWithPort(SsUserType.UserSeq)] =
                    cookieUserDetail[KeyWithPort(SsUserType.UserSeq)] = userSeq;
                HttpContext.Current.Session[KeyWithPort(SsUserType.WorkingJobSiteSeq)] =
                    cookieUserDetail[KeyWithPort(SsUserType.WorkingJobSiteSeq)] = workingJobSiteSeq;
                HttpContext.Current.Session[KeyWithPort(SsUserType.Height)] =
                    cookieUserDetail[KeyWithPort(SsUserType.Height)] = height;
            }
        }

        public void CopyLoginSessionFromEss(int hostPortEss)
        {
            HttpCookie cookieUserDetailEss =
                HttpContext.Current.Request.Cookies[KeyWithPort(SsUserType.UserDetail, hostPortEss)];

            if (cookieUserDetailEss == null) return;

            HttpCookie cookieUserDetailThis = HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)] ??
                HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)];

            if (cookieUserDetailThis == null)
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(KeyWithPort(SsUserType.UserDetail)));

            // Set Cookie 
            // Remark : now if cookieUserDetail == null , meaning Can't create cookie
            if (cookieUserDetailThis != null && cookieUserDetailEss.HasKeys)
            {
                HttpContext.Current.Session[KeyWithPort(SsUserType.EmpSeq)] =
                    cookieUserDetailThis[KeyWithPort(SsUserType.EmpSeq)] =
                    cookieUserDetailEss[KeyWithPort(SsUserType.EmpSeq, hostPortEss)];

                HttpContext.Current.Session[KeyWithPort(SsUserType.UserName)] =
                    cookieUserDetailThis[KeyWithPort(SsUserType.UserName)] =
                    cookieUserDetailEss[KeyWithPort(SsUserType.UserName, hostPortEss)];

                HttpContext.Current.Session[KeyWithPort(SsUserType.UserSeq)] =
                    cookieUserDetailThis[KeyWithPort(SsUserType.UserSeq)] =
                    cookieUserDetailEss[KeyWithPort(SsUserType.UserSeq, hostPortEss)];

                HttpContext.Current.Session[KeyWithPort(SsUserType.WorkingJobSiteSeq)] =
                    cookieUserDetailThis[KeyWithPort(SsUserType.WorkingJobSiteSeq)] =
                    cookieUserDetailEss[KeyWithPort(SsUserType.WorkingJobSiteSeq, hostPortEss)];

                HttpContext.Current.Session[KeyWithPort(SsUserType.Height)] =
                    cookieUserDetailThis[KeyWithPort(SsUserType.Height)] =
                    cookieUserDetailEss[KeyWithPort(SsUserType.Height, hostPortEss)];
            }
        }

        public void SetUss(string key, int value)
        {
            SetUss(key, Convert.ToString(value));
        }

        public void SetUss(string key, string value)
        {
            HttpCookie cookieUserDetail = HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)];

            if (cookieUserDetail == null)
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(KeyWithPort(SsUserType.UserDetail)));

            HttpContext.Current.Session[KeyWithPort(key)] = cookieUserDetail[KeyWithPort(key)] = value;

        }

        public void SetUss(SsUserType ssUserType, int value)
        {
            SetUss(ssUserType, Convert.ToString(value));
        }

        public void SetUss(SsUserType ssUserType, string value)
        {
            HttpCookie cookieUserDetail = HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)];

            if (cookieUserDetail == null)
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(KeyWithPort(SsUserType.UserDetail)));

            HttpContext.Current.Session[KeyWithPort(SsUserType.EmpSeq)] =
                cookieUserDetail[KeyWithPort(SsUserType.EmpSeq)] = value;
        }

        #endregion

        #region Delete Zone

        public void DeleteUss(string key)
        {
            HttpCookie cookieUserDetail = HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)];

            if (cookieUserDetail == null)
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(KeyWithPort(SsUserType.UserDetail)));

            HttpContext.Current.Session.Remove(KeyWithPort(SsUserType.EmpSeq));
            // remark : data still in cookie.
        }

        public void LogoutUss()
        {
            HttpCookie cookie = ReadAndExtendExpireCookie();

            if (cookie != null)
            {
                cookie.Expires = DateTime.Now.AddDays(-1);
            }

            // RadMenu1.Items.Clear();
            HttpContext.Current.Session.Abandon();
            HttpContext.Current.Response.Redirect(GetUrlToRedirect());
        }

        #endregion

        #region Miscellenous

        public void CheckUss() // If not found, GetUss() also do work Redirect to login page
        {
            GetUss(SsUserType.UserName);
        }

        public string GetServerString()
        {
            return HttpContext.Current.Request.Url.Host +
                       (ConfigurationSettings.AppSettings["SubSystem"].Length > 0
                            ? "/" + ConfigurationSettings.AppSettings["SubSystem"]
                            : "") +
                        "/";

        }

        private string KeyWithPort(SsUserType ssUserType, int? portEss = null)
        {
            string port = "";
            if (IncludePortNumberInKey && !portEss.HasValue)
            {
                port = "" + PortNumber;
            }
            else if (portEss.HasValue)
            {
                port = "" + (portEss.Value == 80 ? "" : "" + portEss.Value);
            }
            return String.Format("{0}{1}", ssUserType, port);
        }

        private string KeyWithPort(string key, int? portEss = null)
        {
            string port = "";
            if (IncludePortNumberInKey && !portEss.HasValue)
            {
                port = "" + PortNumber;
            }
            else if (portEss.HasValue)
            {
                port = "" + (portEss.Value == 80 ? "" : "" + portEss.Value);
            }
            return String.Format("{0}{1}", key, port);
        }

        /* breif Method ย้ำไปย้ำมา */
        public HttpCookie ReadAndExtendExpireCookie()
        {
            // โหลด Cookie
            HttpCookie cookieUserDetail = HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)];

            // ถ้า Cookie ไม่ได้ถูกเซต, noCookie = true
            bool noCookie = cookieUserDetail == null || !cookieUserDetail.HasKeys;
            // ถ้า Session ไม่ได้ถูกเซต , noSession = true
            bool noSession = HttpContext.Current.Session[KeyWithPort(SsUserType.UserSeq)] == null ||
                             (string)HttpContext.Current.Session[KeyWithPort(SsUserType.UserSeq)] == "";

            // ประมวลผล #1 : ถ้า Cookie ไม่ได้ถูกเซต Session ไม่ได้ถูกเซต แสดงว่าไม่ได้ Login แน่นอน, ทำการ Redirect ไปหน้า Login
            if (noCookie && noSession)
            {
                HttpContext.Current.Response.Redirect(GetUrlToRedirect());
            }

            // ถ้า Session ไม่ได้ถูกเซต ให้ลองโหลดจาก Cookie
            if (noSession)
            {
                HttpContext.Current.Session[KeyWithPort(SsUserType.EmpSeq)] =
                    cookieUserDetail[KeyWithPort(SsUserType.EmpSeq)];
                HttpContext.Current.Session[KeyWithPort(SsUserType.UserName)] =
                    cookieUserDetail[KeyWithPort(SsUserType.UserName)];
                HttpContext.Current.Session[KeyWithPort(SsUserType.UserSeq)] =
                    cookieUserDetail[KeyWithPort(SsUserType.UserSeq)];
                HttpContext.Current.Session[KeyWithPort(SsUserType.WorkingJobSiteSeq)] =
                    cookieUserDetail[KeyWithPort(SsUserType.WorkingJobSiteSeq)];
                HttpContext.Current.Session[KeyWithPort(SsUserType.Height)] =
                    cookieUserDetail[KeyWithPort(SsUserType.Height)];
            }

            // สร้าง Cookie กรณีที่  Session มีค่า แต่ Cookie ไม่ได้สร้าง
            if (HttpContext.Current.Response.Cookies[KeyWithPort(SsUserType.UserDetail)] == null)
                HttpContext.Current.Response.Cookies.Add(new HttpCookie(KeyWithPort(SsUserType.UserDetail)));

            // สร้าง Cookie ไม่ได้ อาจเป็นเรื่อง Security ในบราวเซอร์ไม่ยอม, ให้จบการทำงานในฟังก์ชั่น เพราะหลังจากนี้เป็นการ Set Cookie
            if (cookieUserDetail == null)
                return null;

            // Set ค่าตาม Parameter
            cookieUserDetail[KeyWithPort(SsUserType.EmpSeq)] =
                (string)HttpContext.Current.Session[KeyWithPort(SsUserType.EmpSeq)];
            cookieUserDetail[KeyWithPort(SsUserType.UserName)] =
                (string)HttpContext.Current.Session[KeyWithPort(SsUserType.UserName)];
            cookieUserDetail[KeyWithPort(SsUserType.UserSeq)] =
                (string)HttpContext.Current.Session[KeyWithPort(SsUserType.UserSeq)];
            cookieUserDetail[KeyWithPort(SsUserType.WorkingJobSiteSeq)] =
                (string)HttpContext.Current.Session[KeyWithPort(SsUserType.WorkingJobSiteSeq)];
            cookieUserDetail[KeyWithPort(SsUserType.Height)] =
                (string)HttpContext.Current.Session[KeyWithPort(SsUserType.Height)];

            // ตั้งเวลาหมดอายุ 1 ชั่วโมง หลังจากการเรียก Method ครั้งนี้
            cookieUserDetail.Expires = DateTime.Now.AddHours(ExpiresHour);

            // Return Cookie ตัวนี้
            return cookieUserDetail;
        }

        string GetUrlToRedirect()
        {
            var url = new StringBuilder(Common.IssueNotLoginUrl);
            // url.Append((url.ToString().Contains("?") ? "&" : "?") + "currenturl=" + HttpUtility.UrlEncode(HttpContext.Current.Request.Url.ToString()));
            return string.IsNullOrWhiteSpace(tempRedirectUrl) ? url.ToString() : tempRedirectUrl;
        }
        #endregion
    }
    
    public static class HttpHelper
    {
        private static BLLMessage bllMessage = new BLLMessage();

        public static int GetMessageUnreadCount(string strEmpSeq)
        {
            string strError = "";
            var message = bllMessage.GetMessage(null, null, null, null, null, null
                                                , false, false, false, false, false, false, out strError);
            int intUnreadCount = (from m in message where m.to_emp_seq.ToString() == strEmpSeq && m.message_status != "0" select m).Count();
            return intUnreadCount;
        }

        public static int GetMessageUnwarnCount(int intEmpSeq)
        {
            using (GERPContext db = new GERPContext())
            {
                string strError = "";
                //var message = bllMessage.GetMessage(null, null, null, null, null, null
                //                                    , false, false, false, false, false, false, out strError);
                int intUnwarnCount = (from m in db.message where m.to_emp_seq == intEmpSeq && m.message_status == "1" select m).Count();
                bllMessage.WarnMessage(intUnwarnCount, intEmpSeq.ToString(), intEmpSeq.ToString());
                return intUnwarnCount;
            }
        }

        /// <summary>
        /// For check whether is in deployed machine or in visual studio, to hide some ui
        /// </summary>
        /// <returns></returns>
        public static bool IsHostHasPost()
        {
            return HttpContext.Current.Request.Url.Port != 80;
        }

        public static hrm_ps_employees GetEmployee(int emp_seq)
        {
            var employeeDal = new Employee();
            return employeeDal.GetHrmPsEmployeeLite(new hrm_ps_employees {emp_seq = emp_seq}).FirstOrDefault();
        }
        public static hrm_ps_employees GetUpperEmployee(int emp_seq)
        {
            var employeeDal = new Employee();
            return employeeDal.GetEmployeesWithUpper().FirstOrDefault();
        }

        public static List<hrm_mp_positions> GetPositions()
        {
            var employeeDal = new Employee();
            return employeeDal.GetHrmMpPositions("", "", "", "", "", "", "", "", false, false, false, false, false,
                                                 false);
        }

        public static hrm_ps_employees GetEmployeeUpperFromLowerPos(int pos_seq, List<hrm_mp_positions> dataPositions, List<hrm_ps_employees> dataEmployees)
        {
            var upperPosition = (from pos in dataPositions where pos.pos_seq == pos_seq select pos).FirstOrDefault();
            if (upperPosition != null)
            {
                var upperEmployee =
                    (from emp in dataEmployees where emp.pos_seq == upperPosition.pos_seq select emp).FirstOrDefault();
                return upperEmployee;
            }
            else
                return null;
        }

        public static int? GetPosSeqFromEmpSeq(int emp_seq)
        {
            var employeeDal = new Employee();
            var employeeList = employeeDal.GetHrmPsEmployeeLite();
            var employeeSpecified = employeeList.FirstOrDefault(o => o.emp_seq == emp_seq);
            if (employeeSpecified != null && employeeSpecified.pos_seq != null)
                return employeeSpecified.pos_seq.Value;
            else return null;
        }

        public static string GetAbsenceType(int absenceTypeSeq)
        {
            var absenceType = new AbsenceTypes().GetAllAbsenceTypes().FirstOrDefault(c => c.absence_type_seq == absenceTypeSeq);
            return absenceType != null ? absenceType.absence_type_name : "";
        }
        public static List<hrm_ps_absence_types> GetAbsenceTypes()
        {
            return new AbsenceTypes().GetAllAbsenceTypes() ?? new List<hrm_ps_absence_types>();
        }

        public static string Substring(string str, int limit = 50, string trailString = "...")
        {
            str = string.IsNullOrWhiteSpace(str) ? "" : str;
            str = str.Trim();
            bool longerThanLimit = str.Length > limit;
            int nonProblemLimit = longerThanLimit ? limit : str.Length;
            str = str.Substring(0, nonProblemLimit) + (str.Length > 0 & longerThanLimit ? trailString : "");
            return str;
        }
    }
}